package com.ibangnuo.manage.service;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.ibangnuo.framework.domain.CommercialTenant;
import com.ibangnuo.framework.domain.User;
import com.ibangnuo.framework.model.response.CommonCode;
import com.ibangnuo.framework.model.response.ResponseResult;
import com.ibangnuo.manage.dao.employee.CommercialRepository;
import com.ibangnuo.manage.service.alipay.PayService;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @Author: wwy
 * @Date: 2020-01-03 10:38
 */
@Service
public class AuthorizationInformationService {
    private static Logger LOGGER = LoggerFactory.getLogger(PayService.class);
    @Value("${third.app_id}")
    private String appId;

    @Value("${third.key.private_key}")
    private String privateKey;

    @Value("${third.key.alipay_public_key}")
    private String alipayPublicKey;

    @Value("${third.gateway}")
    private String gateway;

    @Value("${third.encodedUrl}")
    private String encodedUrl;

    @Value("${third.scope}")
    private String scope;
    @Autowired
    private CommercialRepository commercialRepository;

    /**
     * url拼接
     * @return
     */
    public  String authorization(){
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        CommercialTenant commercialTenant = commercialRepository.findByUserId(user.getId());
        String url = "https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id="+appId+"&scope="+scope+"&redirect_uri="+encodedUrl+"&state="+commercialTenant.getId();
        LOGGER.info("授权url:{}",url);
        return url;
    }

    /**
     * 获取会员信息
     * 1.获取appid
     * 2.根据state(商户主键)数据库，保存appid
     * @param appId
     * @param scope
     * @param authCode
     * @return
     */
    public ResponseResult getAuthInfo(String appId, String scope, String authCode, String state){
        AlipaySystemOauthTokenResponse oauthTokenResponse = this.getAccessToken(authCode);
        if(oauthTokenResponse==null){
            return new ResponseResult(CommonCode.FAIL);
        }
        String accessToken = oauthTokenResponse.getAccessToken();
        String userId = oauthTokenResponse.getUserId();
        CommercialTenant commercialTenant = this.getCommercialTenant(state);

        if(commercialTenant == null){
            LOGGER.error("商户查询为空");
            return null;
        }
        commercialTenant.setPId(userId);
        this.updateCommercialTenant(state,commercialTenant);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    /**
     * 获取accessToken
     * @return
     */
    private AlipaySystemOauthTokenResponse getAccessToken(String authCode){
        String charset = "GBK";
        String sign_type = "RSA2";
        AlipayClient alipayClient = new DefaultAlipayClient(gateway,appId,privateKey,"json",charset,alipayPublicKey,sign_type);
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        request.setCode(authCode);
        request.setGrantType("authorization_code");
        try {
            AlipaySystemOauthTokenResponse oauthTokenResponse = alipayClient.execute(request);
            return oauthTokenResponse;
        } catch (AlipayApiException e) {
            LOGGER.error("获取accessToken接口失败",e.getMessage());
        }
        return null;
    }

    /**
     * 根据id查询用户
     * @param id
     * @return
     */
    private CommercialTenant getCommercialTenant(String id){
        Optional<CommercialTenant> optional = commercialRepository.findById(id);
        if(optional.isPresent()){
            return optional.get();
        }
        return null;
    }

    /**
     * 根据id更新s商户表
     * @param id
     * @param merchantsEntity
     * @return
     */
    private CommercialTenant updateCommercialTenant(String id,CommercialTenant merchantsEntity){
        CommercialTenant save = commercialRepository.save(merchantsEntity);
        return save;
    }
}
